﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NetgameProtocol;
using System.Reflection;
using _2DgameServer.Servers;

namespace _2DgameServer.Controller
{
    class ControllerManager
    {

        //创建列表管理所有的Controller
        private Dictionary<RequestCode, BaseController> controlDict = new Dictionary<RequestCode, BaseController>();
        private Server server;
        public ControllerManager(Server server)
        {
            this.server = server;
            UserController userController = new UserController();
            controlDict.Add(userController.GetResquestCode, userController);

            RoomController roomController = new RoomController();
            controlDict.Add(roomController.GetResquestCode, roomController);

            GameController gameController = new GameController();
            controlDict.Add(gameController.GetResquestCode, gameController);
        }
        //客户端发出登录请求，服务器端通过ActionCode和RequestCode找到对应的方法，然会返回参数给客户端，比如是否登录成功
        public void HandleRequest(MainPack pack, Client client)
        {
            if (controlDict.TryGetValue(pack.RequestCode, out BaseController controller))
            {
                //得到名字
                string metname = pack.ActionCode.ToString();
                
                //发现方法的属性并提供对方法元数据的访问
                //使用 MethodInfo 对象获取有关对象所表示的方法的信息，以及调用方法
                MethodInfo method = controller.GetType().GetMethod(metname);
                //Console.WriteLine(method);
                if (method == null)
                {
                    Console.WriteLine("没有找到对应的处理方法");
                    return;
                }
                object[] obj = new object[] { server, client, pack };
                object ret = method.Invoke(controller, obj);
                if (ret != null)
                {
                    client.Send(ret as MainPack);
                }
            }
            else
            {

                Console.WriteLine("没有找到对应的Controller处理");
            }
        }
    }
}
